package com.wisdytech.linkdcs.equipLifeCycle.maintain.service.impl;

import com.wisdytech.linkdcs.equipLifeCycle.maintain.model.MaintenancePlan;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.model.MaintenanceTask;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.bean.event.EquipEvent;
import com.wisdytech.common.constants.CommonConstants;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.dao.IMaintenancePlanDao;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.dto.MaintenancePlanDTO;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.service.IMaintenancePlanService;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.wisdytech.linkdcs.equipment.model.EquipModel;
import com.wisdytech.linkdcs.equipment.model.Equipment;
import com.wisdytech.linkdcs.equipment.dao.IEqEquipmentDao;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.dao.IMaintenanceTaskDao;
import com.wisdytech.linkdcs.equipment.dao.IEqModelDao;
/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenbin
 * @since 2018-06-10
 */
@Service("iMaintenancePlanService")
@Transactional
public class MaintenancePlanServiceImpl extends BaseService<IMaintenancePlanDao, MaintenancePlan> implements IMaintenancePlanService {

	@Resource
	private IMaintenancePlanDao iMaintenancePlanDao;
	@Resource
	private IEqEquipmentDao iEqEquipmentDao;
	@Resource
	private IMaintenanceTaskDao iMaintenanceTaskDao;
	@Resource
	private IEqModelDao iEqModelDao;
	@Override
	public void addPlan(MaintenancePlanDTO maintenancePlanDTO, String loginName) {
		//新增保养计划
		MaintenancePlan maintenancePlan = new MaintenancePlan();
		String pkId = BaseUtil.getUUID();
		maintenancePlan.setPkId(pkId);
		maintenancePlan.setDelFlag(CommonConstants.DEL_FLAG);
		maintenancePlan.setCreateUser(loginName);
		maintenancePlan.setCreateDate(new Date());
		maintenancePlan.setMaintainConfirm(maintenancePlanDTO.getMaintainConfirm());
		maintenancePlan.setMaintainCycle(maintenancePlanDTO.getMaintainCycle());
		maintenancePlan.setMaintainUserName(maintenancePlanDTO.getMaintainUsername());
		maintenancePlan.setMaintainUserWorkNo(maintenancePlanDTO.getMaintainUserWorkNo());
		maintenancePlan.setModelCode(maintenancePlanDTO.getModelCode());
		maintenancePlan.setPlanStatus(maintenancePlanDTO.getPlanStatus());
		maintenancePlan.setPlanType(CommonConstants.CYCLE_PLAN_TYPE); //周期性计划
		maintenancePlan.setRemark(maintenancePlanDTO.getRemark());
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date date0 = null;
		try {
			date0 = df.parse(maintenancePlanDTO.getStartDate());
			maintenancePlan.setStartDate(date0);
		} catch (ParseException e) {
			e.printStackTrace();
		}  
		maintenancePlan.setTypeId(maintenancePlanDTO.getTypeId());
		int count = iMaintenancePlanDao.insert(maintenancePlan);
        if (count <= 0) {
            throw new ServiceException("新增失败");
        }	

        //新增保养任务
       List<Equipment> listEq = iEqEquipmentDao.selectListByModelCode(maintenancePlanDTO.getModelCode());//获取改型号下的所有设备
       //计划有效时，生成保养任务
       if(maintenancePlan.getPlanStatus().equals("0")) {
           for(Equipment equipment : listEq) {
        	   MaintenanceTask maintenanceTask = new MaintenanceTask();
        	   maintenanceTask.setPkId(BaseUtil.getUUID());
        	   maintenanceTask.setEquipCode(equipment.getEquipCode());
        	   maintenanceTask.setDelFlag(CommonConstants.DEL_FLAG);
        	   maintenanceTask.setNextDate(date0);
        	   maintenanceTask.setPlanId(pkId);
        	   maintenanceTask.setType(CommonConstants.CYCLE_TASK);//周期性保养
        	   maintenanceTask.setTaskStatus(CommonConstants.TASK_NO);//生成还未保养任务
        	   int num = iMaintenanceTaskDao.insert(maintenanceTask);
               if (num <= 0) {
                   throw new ServiceException("新增失败");
               }	
           } 
       }
	}

	@Override
	public PageInfo<MaintenancePlan> listModelPlanByFilter(String modelCode, Filter filter) {
        if(StringUtils.isBlank(modelCode))
            return new PageInfo<>(new ArrayList<>());
        List<MaintenancePlan> list = this.beforeList(IMaintenancePlanDao.class,filter).listModelPlanByFilter(modelCode);
        PageInfo<MaintenancePlan> page = new PageInfo<>(list);
        return page;
	}

	@Override
	public MaintenancePlan getPlanById(String pkId) {
		return iMaintenancePlanDao.getPlanById(pkId);
	}

	@Override
	public void updatePlan(MaintenancePlanDTO maintenancePlanDTO, String loginName) {
		MaintenancePlan maintenancePlan = new MaintenancePlan();
		maintenancePlan.setPkId(maintenancePlanDTO.getPkId());
		maintenancePlan.setUpdateUser(loginName);
		maintenancePlan.setUpdateDate(new Date());
		maintenancePlan.setMaintainConfirm(maintenancePlanDTO.getMaintainConfirm());
		maintenancePlan.setMaintainCycle(maintenancePlanDTO.getMaintainCycle());
		maintenancePlan.setMaintainUserName(maintenancePlanDTO.getMaintainUsername());
		maintenancePlan.setMaintainUserWorkNo(maintenancePlanDTO.getMaintainUserWorkNo());
		maintenancePlan.setModelCode(maintenancePlanDTO.getModelCode());
		maintenancePlan.setPlanStatus(maintenancePlanDTO.getPlanStatus());
//		maintenancePlan.setPlanType(planType); //保养类型
		maintenancePlan.setRemark(maintenancePlanDTO.getRemark());
		Date date0 = null;
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		try {
			date0 = df.parse(maintenancePlanDTO.getStartDate());
			maintenancePlan.setStartDate(date0);
		} catch (ParseException e) {
			e.printStackTrace();
		}  
		maintenancePlan.setTypeId(maintenancePlanDTO.getTypeId());
		int count = iMaintenancePlanDao.updateById(maintenancePlan);
        if (count <= 0) {
            throw new ServiceException("修改失败");
        }	
        //新增保养任务
       List<Equipment> listEq = iEqEquipmentDao.selectListByModelCode(maintenancePlanDTO.getModelCode());//获取改型号下的所有设备
       //计划有效时，生成保养任务
       if(maintenancePlan.getPlanStatus().equals("0")) {

           for(Equipment equipment : listEq) {
        	   //判断改计划是否生成了任务
        	   EntityWrapper<MaintenanceTask> ew = new EntityWrapper<>();
        	   ew.eq("EQUIP_CODE", equipment.getEquipCode());
        	   ew.eq("PLAN_ID", maintenancePlan.getPkId());
        	   int number  = iMaintenanceTaskDao.selectCount(ew);
        	   if(number>0) {
        		   throw new ServiceException("未做任何修改"); 
        	   }
        	   MaintenanceTask maintenanceTask = new MaintenanceTask();
        	   maintenanceTask.setPkId(BaseUtil.getUUID());
        	   maintenanceTask.setEquipCode(equipment.getEquipCode());
        	   maintenanceTask.setDelFlag(CommonConstants.DEL_FLAG);
        	   maintenanceTask.setNextDate(date0);
        	   maintenanceTask.setPlanId(maintenancePlanDTO.getPkId());
        	   maintenanceTask.setType(CommonConstants.CYCLE_TASK);//周期性保养
        	   maintenanceTask.setTaskStatus(CommonConstants.TASK_NO);//生成还未保养任务
        	   int num = iMaintenanceTaskDao.insert(maintenanceTask);
               if (num <= 0) {
                   throw new ServiceException("新增失败");
               }	
           } 
       }
       //计划为无效时，删除该设备型号下的，对应保养任务
       if(maintenancePlan.getPlanStatus().equals("1")) {
           for(Equipment equipment : listEq) {
        	   EntityWrapper<MaintenanceTask> ew = new EntityWrapper<>();
        	   ew.eq("EQUIP_CODE", equipment.getEquipCode());
        	   ew.eq("PLAN_ID", maintenancePlanDTO.getPkId());
        	   iMaintenanceTaskDao.delete(ew);
           } 
       }
	}

	@Override
	public void deletePlanById(String ids) {
        List<String> idList = new ArrayList<String>();
        String[] id = ids.split(",");
        for (int i = 0; i < id.length; i++) {
            idList.add(id[i]);
        }
        for(String pkId : id) {
            //查询保养任务中是否存在已保养的
            EntityWrapper<MaintenanceTask> ew = new EntityWrapper<>();
            ew.eq("TYPE", "0");//保养任务为周期性
            ew.eq("DEL_FLAG", "1");//已被标记为保养过
            ew.eq("PLAN_ID", pkId);
            int num = this.iMaintenanceTaskDao.selectCount(ew);
            if(num>0) {
            	throw new ServiceException("生成的保养任务存在已保养");
            }
        }
        int partCount = iMaintenancePlanDao.deleteBatchIds(idList);
        if (partCount <= 0) {
            throw new ServiceException("删除失败");
        }
		
	}
	
	@EventListener
	protected void 	equipEventListener(EquipEvent equipEvent) {
		switch (equipEvent.getType().getCode()) {
		case 1:
			this.addEqTask(equipEvent);
			break;
		case 2:
			this.updateEqTask(equipEvent);
			break;
		default:
			this.delEqTask(equipEvent);
			break;
		}
	}
	//同步修改保养任务的设备编码
	private void updateEqTask(EquipEvent equipEvent) {
		String equipId = "";
		//查询设备类型
		for(String eqId : equipEvent.getEquipIds()) {
			equipId = eqId;
		}
		String equipCode = "";
		for(String eqCode : equipEvent.getEquipCode()) {
			equipCode = eqCode;
		}
		//获取设备
		Equipment equipment = iEqEquipmentDao.selectById(equipId);
		//获取改设备下的任务
		EntityWrapper<MaintenanceTask> ew = new EntityWrapper<>();
		ew.eq("EQUIP_CODE", equipCode);
		List<MaintenanceTask> list = iMaintenanceTaskDao.selectList(ew);
		if(!list.isEmpty()) {
			for(MaintenanceTask task : list) {
				//修改设备编码
				task.setEquipCode(equipment.getEquipCode());
				iMaintenanceTaskDao.updateById(task);
			}
		}
	}

	//同步生成保养任务
	public void addEqTask(EquipEvent equipEvent) {
		String equipId = "";
		//查询设备类型
		for(String eqId : equipEvent.getEquipIds()) {
			equipId = eqId;
		}
		//获取设备
		Equipment equipment = iEqEquipmentDao.selectById(equipId);
		//获取设备型号
//		EquipModel equipModel = iEqModelDao.selectById(equipment.getModelId());
		//获取改设备型号下计划
		EntityWrapper<MaintenancePlan> ew = new EntityWrapper<>();
		ew.eq("MODEL_CODE", equipment.getModelCode());
		//获取改设备型号下的计划
		List<MaintenancePlan> list = iMaintenancePlanDao.selectList(ew);
		if(!list.isEmpty()) {
			for(MaintenancePlan plan : list) {
			   //给新增设备同步生成保养任务
	    	   MaintenanceTask maintenanceTask = new MaintenanceTask();
	    	   maintenanceTask.setPkId(BaseUtil.getUUID());
	    	   maintenanceTask.setEquipCode(equipment.getEquipCode());
	    	   maintenanceTask.setDelFlag(CommonConstants.DEL_FLAG);
	    	   maintenanceTask.setNextDate(plan.getStartDate());//下次保养时间即为计划中的保养开始时间
	    	   maintenanceTask.setPlanId(plan.getPkId());
	    	   maintenanceTask.setType(CommonConstants.CYCLE_TASK);//周期性保养
	    	   maintenanceTask.setTaskStatus(CommonConstants.TASK_NO);//生成还未保养任务
	    	   int num = iMaintenanceTaskDao.insert(maintenanceTask);
	           if (num <= 0) {
	               throw new ServiceException("新增失败");
	           }
			}

		}
	}
	//同步删除设备的保养的任务
	public void delEqTask(EquipEvent equipEvent) {
		List<String> ipList = equipEvent.getEquipIds();
		for(String pkId : ipList) {
			//获取设备
			Equipment equipment = iEqEquipmentDao.selectById(pkId);
			//获取改设备下的任务
			EntityWrapper<MaintenanceTask> ew = new EntityWrapper<>();
			ew.eq("EQUIP_CODE", equipment.getEquipCode());
			List<MaintenanceTask> list = iMaintenanceTaskDao.selectList(ew);
			if(!list.isEmpty()) {
				int num = iMaintenanceTaskDao.delete(ew);
				if(num<0) {
					throw new ServiceException("删除失败");
				}
			}
		}
	}
}
